#include "resizableimagetextedit.h"
#include <QTextBlock>
#include <QTextDocument>
#include <QDebug>

ResizableImageTextEdit::ResizableImageTextEdit(QWidget *parent)
    : QTextEdit(parent), m_resizingImage(false), m_currentImagePosition(-1)
{
    // 启用鼠标跟踪以检测鼠标是否位于图片角落
    setMouseTracking(true);
}

void ResizableImageTextEdit::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && isMouseOnImageCorner(event->pos())) {
        m_resizingImage = true;
        m_lastPos = event->pos();
        // 设置光标为调整大小形状
        setCursor(Qt::SizeFDiagCursor);
        event->accept();
        return;
    }

    // 调用父类的事件处理
    QTextEdit::mousePressEvent(event);
}

void ResizableImageTextEdit::mouseReleaseEvent(QMouseEvent *event)
{
    if (m_resizingImage) {
        m_resizingImage = false;
        setCursor(Qt::ArrowCursor);
        event->accept();
        return;
    }

    QTextEdit::mouseReleaseEvent(event);
}

void ResizableImageTextEdit::mouseMoveEvent(QMouseEvent *event)
{
    // 先检查是否处于调整图片大小模式
    if (m_resizingImage && m_currentImagePosition >= 0) {
        // 计算大小增量
        QPoint delta = event->pos() - m_lastPos;

        // 使用保存的图片格式
        QTextImageFormat imageFormat = m_currentImageFormat;

        // 设置新的宽度和高度，保持长宽比
        double aspectRatio = static_cast<double>(imageFormat.width()) / imageFormat.height();
        int newWidth = imageFormat.width() + delta.x();
        int newHeight = qRound(newWidth / aspectRatio);

        // 确保图片不会太小
        if (newWidth > 20 && newHeight > 20) {
            imageFormat.setWidth(newWidth);
            imageFormat.setHeight(newHeight);

            // 应用新的格式
            QTextCursor cursor = textCursor();
            cursor.setPosition(m_currentImagePosition);
            cursor.setPosition(m_currentImagePosition + 1, QTextCursor::KeepAnchor);
            cursor.setCharFormat(imageFormat);

            // 更新当前图片格式（保存最新设置的尺寸）
            m_currentImageFormat = imageFormat;

            // 更新最后一次鼠标位置
            m_lastPos = event->pos();
        }

        event->accept();
        return;
    }
    // 如果不是在调整大小，检查鼠标是否在图片角落
    else if (isMouseOnImageCorner(event->pos())) {
        // 设置光标为调整大小形状
        viewport()->setCursor(Qt::SizeFDiagCursor);
        event->accept();
        return;
    } else {
        // 恢复默认光标
        viewport()->setCursor(Qt::ArrowCursor);
    }

    QTextEdit::mouseMoveEvent(event);
}

bool ResizableImageTextEdit::isMouseOnImageCorner(const QPoint &pos)
{
    // 检查鼠标是否在图片的右下角区域
    QTextCursor cursor = cursorForPosition(pos);
    QTextBlock block = cursor.block();

    // 遍历块中的所有格式对象
    for (QTextBlock::iterator it = block.begin(); !it.atEnd(); ++it) {
        QTextFragment fragment = it.fragment();

        if (fragment.isValid()) {
            QTextCharFormat format = fragment.charFormat();

            if (format.isImageFormat()) {
                QTextImageFormat imgFormat = format.toImageFormat();

                // 检查图片是否有有效尺寸
                if (imgFormat.width() <= 0 || imgFormat.height() <= 0) {
                    continue;
                }

                // 获取图片在视口中的位置和大小
                QTextCursor imgCursor(document());
                imgCursor.setPosition(fragment.position());
                QRect imgRect = cursorRect(imgCursor);

                // 调整矩形以匹配图片实际大小
                imgRect.setWidth(imgFormat.width());
                imgRect.setHeight(imgFormat.height());

                // 定义右下角区域的大小
                const int cornerSize = 15; // 增大角落区域的大小
                QRect cornerRect(
                    imgRect.right() - cornerSize,
                    imgRect.bottom() - cornerSize,
                    cornerSize,
                    cornerSize
                );

                // 如果鼠标在角落区域内
                if (cornerRect.contains(pos)) {
                    // 保存当前图片位置和格式
                    m_currentImagePosition = fragment.position();
                    m_currentImageFormat = imgFormat;

                    // 输出调试信息
                    qDebug() << "Found image corner at position:" << fragment.position();
                    qDebug() << "Image size:" << imgFormat.width() << "x" << imgFormat.height();
                    qDebug() << "Corner rect:" << cornerRect;
                    qDebug() << "Mouse pos:" << pos;

                    return true;
                }
            }
        }
    }

    // 如果没找到图片，重置当前图片位置
    m_currentImagePosition = -1;
    return false;
}

// 重写事件过滤器，确保光标样式在整个组件上保持一致
bool ResizableImageTextEdit::viewportEvent(QEvent *event)
{
    if (event->type() == QEvent::CursorChange && m_resizingImage) {
        viewport()->setCursor(Qt::SizeFDiagCursor);
        return true;
    }
    return QTextEdit::viewportEvent(event);
}